/**
 * Dashboard.Post
 * Must handle everything related to posting
 * - includes entry delete as well
 *
 * @author Seth
 * @version 0.8
 */
Dashboard.Post = function() {
	var open = false,
		store = {
			linked: false,
			perm: {
				d: 0,
				u: false
			}
		},

	// link a picture
	_link_picture = function() {
		_link_dialog('picture');

	// link a video
	}, _link_video = function() {
		_link_dialog('video');

	// link a audio
	}, _link_audio = function() {
		_link_dialog('audio');

	// on link
	}, _link_update = function(a, b, p) {
		var u = a == 'video' ? 'http://www.youtube.com/watch?v='+ b : b,
			c = $('[name="attached_'+a+'"]'),
			r = typeof p == "undefined" ? 'link' : 'upload';

		// set store
		store.linked = [a, b, r];

		// hide links and set href
		$('[name*="link_"]').hide();
		c.attr('href', u);
		c.attr('title', u);

		// link too big? truncate it
		if(u.length > 50)
			c.addClass('truncate');

		// set html to linked and show it
		c.html('<span>'+ _translate('attached_'+a) +':</span> ' + u);
		c.show();

		// also show the delete button
		$('[name="attached_delete"]').show();

	// clear linked
	}, _link_clear = function() {
		$('[name*="attached_"]').hide();
		$('[name*="link_"]').show();
		store.linked = false;

	// the link dialog
	}, _link_dialog = function(x) {
    	var identity = 'dialog-attach',

    	// check video function
		__check_video = function(x, y, v) {
    		// http://stackoverflow.com/questions/5830387/php-regex-find-all-youtube-video-ids-in-string
			var	g = /https?:\/\/(?:[0-9A-Z-]+\.)?(?:youtu\.be\/|youtube\.com\S*[^\w\-\s])([\w\-]{11})(?=[^\w\-]|$)(?![?=&+%\w]*(?:['"][^<>]*>|<\/a>))[?=&+%\w]*/ig;
			if(!v.match(g)) {
				y.addClass('box_error');
				return;
			}

			// extract id
			var t = v.replace(g, '$1=+=$1=+=$1').split('=+=');

			// link it and close dialog
			_link_update(x, t[0]);
			$("#"+ identity).dialog("close");

		// check picture function
    	}, __check_picture_and_audio = function(x, y, v) {
			// http://snippets.dzone.com/posts/show/452 (removed ftp & https)
			if(!v.match(/(http|http):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/)) {
				y.addClass('box_error');
				return;
			}

			// set progress and disable button
			y.addClass('box_progress');
			$(":button:contains('"+ _translate('link') +"')").attr("disabled","disabled").addClass("ui-state-disabled");

			// check headers as well
	    	Petolio.ajax({
				url: 'dashboard/check',
				type: 'post',
				data: {x: x, v: v},
				cache: false,
				success: function () {
					// link it and close dialog
					_link_update(x, v);
					$("#"+ identity).dialog("close");
				},
				error: function() {
					y.removeClass('box_progress');
					y.addClass('box_error');
					$(":button:contains('"+ _translate('link') +"')").removeAttr("disabled").removeClass("ui-state-disabled");
				}
			});

	    // the link dialog
    	}, __link_dialog = function() {
        	$("#"+ identity).remove();
    		$('<div id="'+ identity +'" title="'+ _translate('link_'+x) +'" class="ui-state-highlight">'+
				'<div style="margin: 8px 0px 2px 0px; line-height: 18px;">'+
					_translate(x+'_txt') +':'+
					'<div style="float: right; font-size: 11px; color: grey;">('+ _translate('valid_' + x) +')</div>'+
					'<br /><div class="fivepx"></div>'+
					'<input type="text" class="box" name="url" style="width:266px;" maxlength="250" value="'+ (x == 'picture' || x == 'audio' ? 'http://' : 'http://www.youtube.com') +'">'+
				'</div>'+
			'</div>').dialog({
				resizable: false,
				modal: true,
    			width: 300,
    			minHeight: 50,
				buttons: [{
					text: _translate('link'),
					click: function() {
						var y = $('input[name="url"]'),
							v = y.val().trim();

						// remove errors
						y.removeClass('box_error');

						// no url given?
						if(v.length == 0) {
							y.addClass('box_error');
							return;
						}

						// check values
						if(x == 'picture' || x == 'audio') __check_picture_and_audio(x, y, v);
						else __check_video(x, y, v);
					}
				},{
					text: _translate('close'),
					click: function() {
						$(this).dialog("close");
					}
				}],
				close: function() {
					$("#"+ identity).remove();
				},
				open: function() {
					$("#"+ identity).find('input').blur();
					$("#"+ identity).find('input').data('for', x);
				}
			});

    	// the upload dialog
    	}, __upload_dialog = function() {
    		$("#"+ identity).remove();
	    	$('<div id="'+ identity +'" title="'+ _translate('upload_'+x) +'" class="ui-state-highlight">'+
	    		'<div style="margin: 8px 0px 2px 0px; line-height: 18px;">'+
	    			'<form id="dash_upload_form" method="post" enctype="multipart/form-data" action="/dashboard/upload">'+
						_translate(x+'_txt') +':'+
						'<div style="float: right; font-size: 11px; color: grey;">('+ _translate('valid_'+x+'_upload') +')</div>'+
						'<br /><div class="fivepx"></div>'+
			    		'<input name="file" id="dash_upload_file" size="31" type="file" /><br />'+
			    		'<div style="display: none;">'+
			    			'<input type="hidden" name="type" value="'+x+'" />'+
			    			'<input type="submit" name="action" value="Upload" /><br />'+
			    			'<iframe id="dash_upload_target" name="dash_upload_target" src="" style="width:460px;height:500px;border:0px solid #fff;"></iframe>'+
			    		'</div>'+
		    		'</form>'+
	    		'</div>'+
	    	'</div>').dialog({
	    		resizable: false,
	    		modal: true,
	    		width: 302,
	    		minHeight: 50,
	    		buttons: [{
	    			text: _translate('upload'),
					click: function() {
						// no file selected ? show error
						if(!($('#dash_upload_file').val().trim().length > 0)) {
	    					Petolio.showMessage(_translate('upload_'+x+'_empty'));
	    					return;
	    				}

						// autoclick
						$('#dash_upload_form').submit();

						// show loading
						Petolio.showLoading(_translate('upload_loading'), [{
			            	text: _translate('upload_abort'),
			            	click: function() {
			            		location.reload(true);
			    			}
			    		}]);
					}
				}, {
	    			text: _translate('close'),
					click: function() {
						$(this).dialog("close");
					}
				}],
				close: function() {
					$("#"+ identity).remove();
				},
				open: function() {
					$("#"+ identity).find('input').blur();
				}
	    	});

	    	// after picture upload callback
	    	$('#dash_upload_target').load(function() {
	    		var d = $.parseJSON($(this).contents().find('body').html());

	    		// response cannot be null
	    		if(d == null)
	    			return false;

	    		// got response, hide loading
	    		Petolio.hideLoading();
	    		if(d.success) {
	    			_link_update(x, d.location, true);
	    			$("#"+ identity).dialog("close");
	    		} else Petolio.showMessage(d.msg);
	    	});
	    };

    	// picture ? choose between upload and link
    	if(x == 'picture' || x == 'audio') {
	    	$('<div id="'+ identity +'" title="'+ _translate('attach_'+x) +'" class="ui-state-highlight">'+
	    		'<div style="margin: 8px 0px 2px 0px; line-height: 18px;">'+
	    			'<span style="float: left; margin-right: 5px; margin-bottom: 100px;" class="ui-icon ui-icon-info"></span>'+
	    			_translate('attach_'+x+'_txt') +
	    			'<br /><br />' +
	    			'<div class="left" id="link_file" style="width: 120px; padding: 20px 10px; border: 2px solid #ff6600; text-align: center; color: #ff6600; cursor: pointer; margin-right: 10px;">'+ _translate('link_'+x) +'</div>' +
	    			'<div class="left" id="upload_file" style="width: 120px; padding: 20px 10px; border: 2px solid #455268; text-align: center; color: #455268; cursor: pointer;">'+ _translate('upload_'+x) +'</div>' +
	    			'<div class="clear"></div>'+
	    		'</div>'+
	    	'</div>').dialog({
	    		resizable: false,
	    		modal: true,
	    		width: 350,
	    		minHeight: 50,
	    		buttons: [{
	    			text: _translate('close'),
					click: function() {
						$(this).dialog("close");
					}
				}],
	    		close: function() {
	    			$("#"+ identity).remove();
	    		}
	    	});

	    	// bind on click
	    	$('#link_file').click(__link_dialog);
	    	$('#upload_file').click(__upload_dialog);

	    // video ? link directly
    	} else __link_dialog();

	// entry post
	}, _entry_post = function() {
		var a = $(this).closest('div.post_entry'),
			x = a.find('div:first'),
			t = a.find('textarea'),
			v = t.val().trim();

		// remove error
		x.removeClass('error');
		x.addClass('normal');

		// no value?
		if(v == _translate('post_blank') || v.length == 0){
			x.removeClass('normal');
			x.addClass('error');
			return;
		}

		// send the post
		Dashboard.Main.load(a);
    	Petolio.ajax({
			url: 'dashboard/post',
			type: 'post',
			data: {v: v, l: store.linked, p: store.perm},
			cache: false,
			success: function () {
				x.find('div').hide();
				t.val(_translate('post_blank'));
				t.height(15);
				_link_clear();
				Dashboard.Main.reload();
			}
		});

	// textarea focus
	},	_focus = function() {
		if($(this).val() == _translate('post_blank')) {
			$(this).val('');
			$(this).height(44);
			$(this).closest('div').find('div').show();
		}

	// textarea blur
	},	_blur = function() {
		if(!$(this).val())
			$(this).val(_translate('post_blank'));

	// open privacy dropdown
	}, _open = function() {
		var x = $(this);

		// close other privacy dialogs
		$('div.entry').find('span.privacy_wrap').each(function(k, v) {
			Dashboard.Privacy.close($(v));
		});

		// already opened somewhere? close that.
		if(open) return _close();

		// open
		x.addClass('privacy_down');
		x.find('ul').show();
		$(x.find('i').get(1)).removeClass().addClass('p_up');

		// set as opened
		open = true;
		return false;

	// close privacy dropdown
	}, _close = function() {
		var x = $("div.post_entry span.privacy_wrap");

		x.removeClass('privacy_down');
		x.find('ul').hide();
		$(x.find('i').get(1)).removeClass().addClass('p_down');

		open = false;

	// save privacy permissions
	}, _save_privacy = function() {
		var x = $(this),
			v = x.find('i').attr('class').replace(' margin', ''),
			b = x.closest('div.entry').data('id');

		// load custom dialog for custom state
		if(v == 'p_custom') {
			Dashboard.Privacy.Custom.init(x, b, Dashboard.Privacy.findPerm(v), v, Dashboard.Post);
			return true;
		}

		// skip save if we click the same state again
		if(x.hasClass('active'))
			return true;

		// save
		store.perm = {d: Dashboard.Privacy.findPerm(v), u: false};
		Dashboard.Privacy.changeState(x, v);

	// save perm from custom
	}, _save_perm = function(x) {
		store.perm = x;

	// url input focus
	},	_url_focus = function() {
		var x = $(this).data('for');

		if($(this).val() == (x == 'picture' ? 'http://' : 'http://www.youtube.com'))
			$(this).val('');

	// url input blur
	},	_url_blur = function() {
		var x = $(this).data('for');

		if(!$(this).val())
			$(this).val(x == 'picture' ? 'http://' : 'http://www.youtube.com');

	// bind
	}, _bind = function() {
		// on post
		$("div.post_entry").delegate('[name="entry_post"]', 'click', _entry_post);

		// link picture or video or audio
		$("div.post_entry").delegate('[name="link_picture"]', 'click', _link_picture);
		$("div.post_entry").delegate('[name="link_video"]', 'click', _link_video);
		$("div.post_entry").delegate('[name="link_audio"]', 'click', _link_audio);

		// focus blur link url
		$("html").delegate('[name="url"]', 'focus', _url_focus);
		$("html").delegate('[name="url"]', 'blur', _url_blur);

		// overwrite return false from divs on these links
		$("div.post_entry").delegate('[name="attached_picture"], [name="attached_video"], [name="attached_audio"]', 'click', function() {
			var f = $(this).attr('href'),
				a = function(){
					if(!window.open(f))
						location.href = f;
				};

			if(/Firefox/.test(navigator.userAgent)) setTimeout(a,0);
			else a();

			// stop bubble
			return false;
		});

		$("div.post_entry").delegate('[name="attached_delete"]', 'click', _link_clear);

		// privacy events
		$("div.post_entry").delegate('span.privacy_wrap', 'click', _open);
		$("div.post_entry").delegate('span.privacy_wrap > ul > li', 'click', _save_privacy);

		// behave as buttons
		$('div.post_entry > span.privacy_wrap').disableSelection();

		// entry controller
		$("div.post_entry").delegate('[name="post_body"]', 'focus', _focus);
		$("div.post_entry").delegate('[name="post_body"]', 'blur', _blur);

		// body click
		$("html").delegate('body', 'click', function(e) {
			var y = $('div.post_entry > div'),
				x = y.find('textarea'),
				z = $(e.target).closest('div.post_entry').length > 0 || $(e.target).closest('div.ui-dialog').length > 0 || $(e.target).hasClass('ui-widget-overlay');

			// close privacy
			_close();

			// close post if blank or ""
			if((x.val() == _translate('post_blank') || x.val().length == 0) && z == false) {
				y.removeClass('error');
				y.addClass('normal');
				x.height(15);
				x.closest('div').find('div').hide();
				_close();
			}
		});

    	// on picture upload submit callback
    	$("html").delegate('#dash_upload_form', 'submit', function() {
    		$('#dash_upload_form').get(0).target = 'dash_upload_target';
    	});

    	// override event bubble
    	$("html").delegate('#dash_upload_form #dash_upload_file', 'click', function(e) {
    		window.onerror = function() {
    			return true;
    		};

    		e.click();
    	});

		// listen for dashboard loading
		$("body").bind("Dashboard", function(e){
			if(e.loading === true) Dashboard.Main.load($("div.post_entry"));
			if(e.loading === false) Dashboard.Main.unload($("div.post_entry"));
		});

    // translate
	}, _translate = function(i) {
		return Dashboard.Translate.init(i);

	// constructor
	}, __construct = function() {
		_bind();
	};

	// public
	return {
		init: __construct,
		savePerm: _save_perm,
		close: _close,
		store: function(){
			return store;
		}
	};
}();